package mysql

import (
	"fmt"
	"strconv"
	"strings"
)

type Node struct {
	Id         uint `gorm:"column:id;primary_key" json:"id" form:"id"`
	Status     int  `gorm:"column:status" json:"status" form:"status"`
	Deleted    int  `gorm:"column:deleted" json:"deleted"`
	AddTime    int32 `gorm:"column:add_time" json:"add_time"`
	UpdateTime int32 `gorm:"column:update_time" json:"update_time"`
	Memo       string `gorm:"column:memo" json:"memo" form:"memo"`
	No         string `gorm:"column:no" json:"no"`
	Level      int    `gorm:"column:level" json:"level"`
	Pid        int    `gorm:"column:pid" json:"pid" form:"pid"`
	Path       string `gorm:"column:path" json:"path" form:"path"`
	Title      string `gorm:"column:name" json:"title" form:"name"`
	Module     string `gorm:"column:module" json:"module"`
	Controller string `gorm:"column:controller" json:"controller"`
	Action     string `gorm:"column:action" json:"action"`
	Method     string `gorm:"column:method" json:"method" form:"method"`
	Params     string `gorm:"column:params" json:"params"`
	Type       int    `gorm:"column:type" json:"type" form:"type"`
	Href       string `gorm:"column:url" json:"href" form:"url"`
	Target     string `gorm:"column:target" json:"target" form:"target"`
	Icon       string `gorm:"column:icon" json:"icon" form:"icon"`
	Tip        string `gorm:"column:tip" json:"tip"`
	Hide       int    `gorm:"column:hide" json:"hide"`
	Selected   int    `gorm:"column:selected" json:"selected" form:"selected"`
	Isaction   int    `gorm:"column:isaction" json:"isaction" form:"isaction"`
	Islogin    int    `gorm:"column:islogin" json:"islogin" form:"islogin"`
	Px         int    `gorm:"column:px" json:"px" form:"px"`
	Child      []Node `json:"child"`

}

//这一步的意思是改表明的  默认表明是带s的
func (Node) TableName() string {
	return "k_admin_sys_node"
}

func (n Node) Sort(id int, px int) error {
	db := Db
	node := Node{}
	err := db.Model(&node).Where("id = ?", id).Update("px", px).Error
	return err
}

func (n Node) SetStatus(id int, status int) error {
	db := Db
	node := Node{}
	err := db.Model(&node).Where("id = ?", id).Update("status", status).Error
	return err
}

func (n Node) Add(node Node) error {
	db := Db
	err := db.Create(&node).Error
	return err
}

func (n Node) Save(node Node) error {
	db := Db
	err := db.Save(&node).Error
	return err
}

func (n Node) Del(id int) error {
	db := Db
	node := Node{}
	err := db.Where("id = ?", id).Delete(&node).Error
	return err
}

func (n Node) GetItemById(id int) (Node, error) {

	db := Db
	node := Node{}
	err = db.Find(&node, id).Error
	if err != nil {
		fmt.Println("查询错误", err)
		return node, err
	}
	return node, err

}

func (n Node) GetItem(path interface{}) (Node, error) {
	db := Db
	node := Node{}
	err = db.Where("url = ?", path).Find(&node).Error

	if err != nil {
		fmt.Println("查询错误", err)
		return node, err
	}
	return node, err
}

func (n Node) GetNodesByIds(ids interface{}) []Node {
	node := []Node{}

	db := Db
	db = db.Where("status = ?", 1)
	db = db.Where("id in (?)", ids)
	db = db.Where("type > ?", 0)

	db.Select("id,pid,name,icon,url,target").Order("px asc").Find(&node)

	if err != nil {
		fmt.Println("查询错误", err)
		return node
	}

	return node
}

func (a Node) BuildMenuChild(pid int, nodes []Node) []Node {
	var path string = "/"
	treelist := []Node{}

	for _, s := range nodes {

		if path == "/" && s.Href != "" {
			s.Href = "/" + s.Href
		}
		if pid == s.Pid {
			childlist := a.BuildMenuChild(int(s.Id), nodes)
			if childlist != nil {
				s.Child = childlist
			}
			treelist = append(treelist, s)
		}
	}
	return treelist

}

func (n Node) GetPidMenuList() ([]Node, error) {

	node := []Node{}
	db := Db
	err := db.Where("type > ?", 0).Where("status = ?", 1).Order("level asc").Order("px desc").Find(&node).Error
	newNodes := n.buildPidMenu(0, node, 0)
	return newNodes, err
}

func (n Node) buildPidMenu(pid int, nodes []Node, level int) []Node {

	tempNodes := []Node{}

	for _, node := range nodes {
		if node.Pid == pid {
			level++
			for _, tn := range tempNodes {
				if node.Pid == tn.Pid {
					level = tn.Level
					break
				}
			}
			node.Level = level
			if level > 1 {
				repeatString := "------"
				old := repeatString + "|" + repeatString
				nums := level - 1
				markString := strings.Repeat(old, nums)
				node.Title = markString + node.Title
			}

			tempNodes = append(tempNodes, node)

			chlildNodes := n.buildPidMenu(int(node.Id), nodes, level)

			if chlildNodes != nil && tempNodes != nil {
				tempNodes = append(tempNodes, chlildNodes...)
			}
		}
	}
	return tempNodes
}

func (node Node) GetNodeListByRoldId(Rold int) []map[string]interface{} {

	list := []map[string]interface{}{}

	ids := AdminNodeItem{}.GetNodesByRoleId(uint(Rold))

	nodes := []Node{}

	db := Db
	db = db.Where("status = ?", 1)

	if len(ids) > 0 {
		db = db.Where("id in (?)", ids)
	}
	db = db.Where("type = ?", 2)

	db.Order("px asc").Find(&nodes)

	for _, ns := range nodes {
		temp := map[string]interface{}{}
		temp["id"] = ns.Id
		temp["pid"] = ns.Pid
		temp["field"] = "node"
		temp["spread"] = true
		temp["type"] = ns.Type
		flag := false
		for _,id := range ids {
			if strconv.Itoa(int(ns.Id)) == id {
				flag = true
				break
			}
		}
		temp["checked"] = flag
		temp["title"] = ns.Title+"【"+ns.Href+"】"
		temp["children"] = node.getChildNodeList(int(ns.Id),ids)
		list = append(list,temp)

	}

	return list
}


func (model Node) getChildNodeList(pid int,ids []string) []map[string]interface{} {

	nodes := []Node{}
	db := Db
	db = db.Where("status = ?", 1)
	db = db.Where("pid = ?", pid)
	db.Order("px asc").Find(&nodes)

	list := []map[string]interface{}{}

	for _, ns := range nodes {
		temp := map[string]interface{}{}
		temp["id"] = ns.Id
		temp["pid"] = ns.Pid
		temp["field"] = "node"
		temp["spread"] = true
		temp["type"] = ns.Type
		flag := false
		for _,id := range ids {
			if strconv.Itoa(int(ns.Id)) == id {
				flag = true
				break
			}
		}
		temp["checked"] = flag
		temp["title"] = ns.Title+"【"+ns.Href+"】"
		temp["children"] = model.getChildNodeList(int(ns.Id),ids)
		list = append(list,temp)
	}
    return list
}